package bin_tree.NewCoder;

import java.util.Scanner;

// 根据先序遍历结果还原二叉树，输出中序遍历结果
public class KY11 {
    private static class TreeNode {
        char val;
        TreeNode left;
        TreeNode right;
        public TreeNode(char val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 获取用户多组输入
        while (scanner.hasNext()) {
            // 字符串形式的先序二叉树结果
            String line = scanner.next();
            // str -> TreeNode
            TreeNode root = build(line);
            // 中序遍历二叉树，按照格式打印结点值
            inOrder(root);
            // 每个结果占一行
            System.out.println();
        }
    }

    private static void inOrder(TreeNode root) {
        if (root == null)
            return;
        inOrder(root.left);
        System.out.print(root.val +" ");
        inOrder(root.right);
    }

    // 根据先序遍历结果字符串还原二叉树，返回构建后二叉树的根节点
    private static TreeNode build(String line) {
        return preOrderBuild(line);
    }
    // abc##de#g##f###
    // str -> char
    // 当前处理到哪个字符了
    static int index = 0;
    private static TreeNode preOrderBuild(String line) {
        char c = line.charAt(index);
        if (c == '#') {
            return null;
        }
        TreeNode root = new TreeNode(c);
        index ++;
        root.left = preOrderBuild(line);
        index ++;
        root.right = preOrderBuild(line);
        return root;
    }
}
